package cn.gov.scds.util;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.imageio.ImageIO;

import org.textmining.text.extraction.WordExtractor;

/*
 * 获取远程文件工具
 * */
public class RemoteFileUtil {
	/** 
	* 通过HTTP方式获取文件 
	* 
	* @param strUrl 
	* @param fileName 
	* @return 
	* @throws IOException 
	*/ 
	
	
	public static boolean getRemoteFile(String strUrl, String fileName,int flag,String filePath) { 
	   //return readWriteWord(strUrl, fileName);
		try {
			getImage(strUrl,fileName,flag,filePath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	/*
	 * 读取Word文档。
	 * */
	public static boolean readWriteWord(String strUrl, String fileName){
		   System.out.println("地址："+strUrl);
		   URL url = null;
		   HttpURLConnection conn = null;
		   String ContetType ="octet-stream;charset=utf-8";
		   DataInputStream input = null;
		   DataOutputStream output = null;
		   
		try {
			
            url = new URL(strUrl);
			
			//打开连接
			try {
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestProperty(ContetType, ContetType);//设置连接请求的类型属性
				
				conn.setRequestMethod("POST");
				
				input = new DataInputStream(conn.getInputStream());
				
				output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("D://AppData/SCDS/Appendix/"+fileName),1024*8));
				
				byte[] buffer = new byte[1024*8];
				   int count = 0;
					while ((count = input.read(buffer)) > 0) {
					      output.write(buffer, 0, count);
					}
				
				output.close();
				input.close();
				
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				System.out.println("*******连接，打开失败............");
			}
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			System.out.println("=============抱歉，附件抓取失败！......");
		}
		
		   return true;
	}
	
	private static boolean getImage(String strUrl,String fileName,int flag,String filePath){
		URL url = null;
		try {
			url = new URL(strUrl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        //打开链接 
        HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection)url.openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //设置请求方式为"GET"
        try {
			conn.setRequestMethod("GET");
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //超时响应时间为5秒 
        conn.setConnectTimeout(20 * 1000);
        //通过输入流获取图片数据 
        InputStream inStream = null;
		try {
			inStream = conn.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性 
        byte[] data = null;
		try {
			data = readInputStream(inStream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //new一个文件对象用来保存图片，默认保存当前工程根目录
		
        File imageFile=null;
        if(flag==0){
        	fileName=fileName.replace("dishui", "");
        	String[] cfStr=fileName.split("/");
        	//String myFilePath=cfStr[1]+"/"+cfStr[2]+"/"+cfStr[3];
        	System.out.println("打印出来："+filePath);
        	File  fileDirectory = new File("D://AppData/SCDS/Appendix/"+filePath);
        	//如果文件夹不存在则创建    
        	if(!fileDirectory.exists()&&!fileDirectory.isDirectory())
        	{
        	    System.out.println("不存在:"+"D://AppData/SCDS/Appendix/"+filePath+"目录，将会新建。");
        	    fileDirectory.mkdirs();
        	}else
        	{
        	    System.out.println("//目录存在");
        	}
        	imageFile = new File("D://AppData/SCDS/Appendix/"+filePath+"/"+fileName);
        	System.out.println("附件图片处理："+imageFile);
        }
        if(flag==1){
        	//imageFile = new File("D://Tomcat 7.0/webapps/data/attachment/"+fileName);
          File	fileDirectory = new File("D://tomcat 7.0/webapps"+filePath);
        	//如果文件夹不存在则创建    
        	if(!fileDirectory.exists()&&!fileDirectory.isDirectory())
        	{
        	    System.out.println("不存在:"+"D://tomcat 7.0/webapps"+filePath+"目录，将会新建。");
        	    fileDirectory.mkdirs();
        	}else
        	{
        	    System.out.println("//目录存在");
        	}
        	imageFile = new File("D://tomcat 7.0/webapps"+filePath+"/"+fileName);
        }
        //创建输出流 
        FileOutputStream outStream = null;
		try {
			outStream = new FileOutputStream(imageFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //写入数据
        try {
			outStream.write(data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //关闭输出流
        try {
			outStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        return true;
	}
	
	/**
     * 获取网络上的图片
     * @param URLName 地址
     * @throws Exception
     */
    public static InputStream getUrlImg(String URLName) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int HttpResult = 0; //服务器返回的状态
        URL url = new URL(URLName); //创建URL
        URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        HttpResult = httpconn.getResponseCode();
        System.out.println(HttpResult);
        if (HttpResult != HttpURLConnection.HTTP_OK){  //不等于HTTP_OK说明连接不成功
            System.out.print("连接失败！");
        }else {
            int filesize = urlconn.getContentLength();  //取数据长度
            System.out.println(filesize); 
            BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream()); 
            BufferedOutputStream bos=new BufferedOutputStream(os);
            byte[] buffer = new byte[1024]; //创建存放输入流的缓冲
            int num = -1; //读入的字节数
            while (true) {
                num = bis.read(buffer); // 读入到缓冲区
                if (num ==-1){
                    bos.flush();
                    break; //已经读完
                }
                bos.flush();
                bos.write(buffer,0,num);
            }
            
            bos.close();
            bis.close();
      } 
      ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
      return bis;
    }
    
    public static byte[] readInputStream(InputStream inStream) throws Exception{
    	ByteArrayOutputStream outStream=null;
    	try{
        outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024*10];  
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
    	}catch(Exception e){
    		System.out.println("图片读取失败！");
    	}
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }
}
